package com.ycyoes.test.image.test;

import cn.hutool.core.img.Img;
import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.photo.Photo;

import java.util.ArrayList;
import java.util.List;

import static org.opencv.imgcodecs.Imgcodecs.imread;
import static org.opencv.imgcodecs.Imgcodecs.imwrite;

public class HutoolRemoveImage {
    static {
//        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // 得保证先执行该语句，用于加载库，才能调用其他操作库的语句，
        System.load("D:\\soft_install\\opencv\\opencv\\build\\java\\x64\\opencv_java480.dll");
    }

    public static void main(String[] args) {
        // 读取原始图像
        Mat originalImage = imread("E:\\pictures\\test\\before.png");

        // 去除水印
        Mat watermarkRemovedImage = removeWatermark(originalImage);

        // 保存结果
        imwrite("E:\\pictures\\test\\output.png", watermarkRemovedImage);
    }

    public static Mat removeWatermark(Mat originalImage) {
        // 实现去除水印的算法
        Mat grayImage = new Mat();
        Imgproc.cvtColor(originalImage, grayImage, Imgproc.COLOR_BGR2GRAY);

        Mat edges = new Mat();
        Imgproc.Canny(grayImage, edges, 50, 150);

        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(edges, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

        Mat mask = new Mat(edges.rows(), edges.cols(), CvType.CV_8UC1, new Scalar(255));
        Imgproc.drawContours(mask, contours, -1, new Scalar(0), -1);

        Mat result = new Mat();
        Photo.inpaint(originalImage, mask, result, 3, Photo.INPAINT_NS);

        return result;
    }
    public static Mat removeWatermark1(Mat originalImage) {
        // 实现去除水印的算法
        Mat grayImage = new Mat();
        Imgproc.cvtColor(originalImage, grayImage, Imgproc.COLOR_BGR2GRAY);

        Mat binaryImage = new Mat();
        Imgproc.adaptiveThreshold(grayImage, binaryImage, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 10);

        Mat dilateImage = new Mat();
        Imgproc.dilate(binaryImage, dilateImage, new Mat(), new Point(-1, -1), 3);

//        Imgproc.GaussianBlur(originalImage, blurredImage, new Size(15, 15), 0);

        return dilateImage;
    }
}

